package org.example.pack;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p> Netty 时间服务器 </p>
 *
 * @author Chris
 * @since 2024/3/25 17:12
 */
public class TimeServer {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(TimeServer.class);

    public void bind(int port) throws InterruptedException {
        // 配置服务端的 NIO 线程组
        // 用于接收客户端的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 用户进行 SocketChanel 的网络读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 辅助启动类：用于启动 NIO 服务端
            final ServerBootstrap b = new ServerBootstrap();
            // 传入线程组
            b.group(bossGroup, workerGroup)
                    // 指定通道
                    .channel(NioServerSocketChannel.class)
                    // 设置 TCP 参数
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 绑定 I/O 事件的处理类
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new LineBasedFrameDecoder(1024))
                                    .addLast(new StringDecoder())
                                    .addLast(new TimeServerHandler());
                        }
                    });

            // 绑定端口，同步等待成功
            final ChannelFuture f = b.bind(port).sync();

            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;

        if (ArrayUtils.isNotEmpty(args)) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                log.error("error=", e);
            }
        }

        new TimeServer().bind(port);
    }
}
